
import axios, { AxiosRequestConfig } from 'axios';
import qs from 'qs';

//存储每个请求的取消函数和唯一键
const pendingRequests=new Map<string,AbortController>();
// 存储每个请求的取消函数和唯一键
export const getPendingUrl = (config: AxiosRequestConfig) => {
    return [config.method, config.url,qs.stringify(config.data),qs.stringify(config.params)].join('&');
}

//取消请求
export class AxiosCancel{
    //创建请求
    addPendingRequest = (config: AxiosRequestConfig) => {
        //取消重复请求
        this.cancelRequest(config);
        // 存储请求
        const url = getPendingUrl(config);
        const controller = new AbortController();
        config.signal = controller.signal;
        // 把当前请求添加到数组中
        if(!pendingRequests.has(url)){
            pendingRequests.set(url, controller);
        }
    }
    // 移除请求
    removePendingRequest = (config: AxiosRequestConfig) => {
        const url = getPendingUrl(config);
        if (pendingRequests.has(url)) {
            const controller = pendingRequests.get(url);
            controller?.abort();
            // 从存储中移除
            pendingRequests.delete(url);
        }
    }
    //取消请求
    cancelRequest = (config: AxiosRequestConfig) => {
        const url = getPendingUrl(config);
        if (pendingRequests.has(url)) {
            // 取消请求
            pendingRequests.get(url)?.abort();
            // 从存储中移除
            pendingRequests.delete(url);
        }
    }
    //取消所有请求
    cancelAllRequests = () => {
        pendingRequests.forEach(controller=>{
            controller.abort();
        });
        // 清空存储
        pendingRequests.clear();
    }
}

